<template>
    <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
             <!--v-collapse="true"-->
            <el-form :model="formInline" class="formInline" ref="formInline" :rules="rules" label-width="90px" slot="form">          
                 <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="所属省" prop="fProvinceId">
                            <province v-model="formInline.fProvinceId"></province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属市">
                            <city v-model="formInline.fCityId" :province="formInline.fProvinceId"></city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="所属区县">
                            <region v-model="formInline.fAreaId" :city="formInline.fCityId"></region>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41"> 
                    <el-col :span="8">
                        <el-form-item label="学校名称">
                             <school v-model="formInline.schoolName" :provinceId="formInline.fProvinceId" :cityId="formInline.fCityId" :areaId="formInline.fAreaId" style="width:100%" @change='schoolChange'></school>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="卡号" prop="sCardNumber">
                            <el-popover placement="top-start" trigger="focus" content="字符长度不大于20个">
                                <el-input v-model="formInline.sCardNumber" placeholder="请输入卡片卡号" :maxlength="10" slot="reference"></el-input>
                            </el-popover>     
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="姓名">
                            <el-popover placement="top-start" trigger="focus" content="字符长度不大于6个">
                                <el-input v-model="formInline.userName" placeholder="请输入教师姓名" :maxlength="6" slot="reference"></el-input>
                            </el-popover>     
                        </el-form-item>
                    </el-col> 
                </el-row>
                <el-row class="top-line">
                    <el-col :span="4" :offset="20"> 
                        <el-button type="primary" class="top-btn" @click="onSubmit('formInline')">查询</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <div class="table-title" slot="table-title">
                <div class="btnPosition">
                    <el-button  @click="goToAdd">单卡绑定</el-button>
                    <el-button  @click="goToAddRole">批量绑定</el-button>
                    <el-button  @click="goToDelRole">批量解绑</el-button>
                    <el-button  @click="goToExport">批量导出</el-button>
                </div>
                <div class="btnPosition">
                    <el-button  @click="showInstruction">卡片说明</el-button>
                </div>
            </div>
            <el-table ref="multipleTable" :data="dataApply" border style="width: 100%" @selection-change="handleSelectionChange" v-loading="loading">

                <el-table-column type="selection" width="55" align="center"></el-table-column>
                
                <el-table-column align="center" prop="schoolName" label="学校名称"></el-table-column>

                <el-table-column align="center" prop="areaName" label="所在地区"></el-table-column>

                <el-table-column align="center" prop="userName" label="教师姓名"></el-table-column>

                <el-table-column align="center" prop="sType" label="卡身份">
                    <template scope="scope">
                        <span>{{scope.row.sType === '0'? '学生卡':scope.row.sType === '1'? '教师卡':scope.row.sType === '2'? '管理员卡':'--'}}</span>
                    </template>
                </el-table-column>

                <el-table-column align="center" prop="sCardNumber" label="卡号"></el-table-column>

                <el-table-column align="center" prop="sCardType"  label="卡片类型">
                    <template scope="scope">
                        <span>{{scope.row.sCardType === '0'? 'IC卡':scope.row.sCardType === '1'? 'ID卡': scope.row.sCardType === '2'? '双频卡':scope.row.sCardType === '3'? '虚拟卡':'--'}}</span>
                    </template>
                </el-table-column>

                <el-table-column align="center" prop="sIsInstall" label="一卡通">
                    <template scope="scope">
                        <span v-if="scope.row.sIsInstall === '2'">--</span>
                        <span v-if="scope.row.sIsInstall === '0'">是</span>
                        <span v-if="scope.row.sIsInstall === '1'" class="link-src btn" @click = "toSetCard(scope.row)">设为一卡通</span>
                    </template>
                </el-table-column>
                
                <el-table-column align="center" prop="sStatus"  label="卡片状态">
                    <template scope="scope">
                        <span v-if="scope.row.sStatus === '3'">正常</span>
                        <span v-if="scope.row.sStatus === '0'">已发放</span>
                        <span v-if="scope.row.sStatus === '1'">未发放</span>
                        <span v-if="scope.row.sStatus === '2'">已挂失</span>
                    </template>
                </el-table-column>
                
                <el-table-column align="left" label="操作">
                    <template scope="scope">
                        <!--v-if="scope.row.sCardType === '0'"-->
                        <span class="link-src btn" @click = "releaseCard(scope.row)">解绑</span>
                    </template>
                </el-table-column>
                 
            </el-table>
            <div class="pagination-container" style="text-align:right">
                    <el-pagination
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="listQuery.total"
                        :current-page.sync="listQuery.page"
                        :page-sizes="config.pageSizes"
                        :page-size="config.pageSize"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange">
                    </el-pagination>
            </div>
        </TableLayout>
        <!--<rejectCheck :dialog="dialog"  @addSuccess='addSuccess' @reviseSuccess='reviseSuccess' ref='addSchoolLeader'></rejectCheck>-->

        <!--卡片说明-->
        <el-dialog title="卡片说明" :visible.sync="dialog.dialogFormVisible1" size="tiny">
            <div class='checkImg2'>
                <table class='dialogTable'>
                    <tr><th style = 'width:100px'>卡片类型</th><th style = 'width:400px'>可刷设备</th><th style = 'width:300px'>备注</th></tr>
                    <tr><td>IC卡</td><td>闸机、接送机、1.0班班通、智慧班牌、e学云校车</td><td>仅IC卡可设为一卡通，每位教师只能有一张卡为一卡通。</td></tr>
                    <tr><td>ID卡</td><td>2.4G考勤机、无障碍考勤机</td><td></td></tr>
                    <tr><td>双频卡</td><td>多人无障碍考勤机</td><td></td></tr>
                    <tr><td>虚拟卡</td><td>嵌入式智能人脸识别终端</td><td>虚拟卡不可以成为一卡通</td></tr>
                </table>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialog.dialogFormVisible1=false">关闭</el-button>
            </div>
        </el-dialog> 

        <!--绑卡-->
        <bindteaCard @importCardState="importCardState" v-if="dialog.dialogFormVisible2" :bindCard="bindCard"></bindteaCard>

        <!--批量绑卡-->
        <batchBind @importCardState="importCardState" v-if="dialog.dialogFormVisible3" :batchBind="batchBind"></batchBind>
        
        <!--批量导出-->
        <batchExport v-if="dialog.dialogFormVisible4" :batchExport="batchExport"></batchExport>

        <!-- 删除弹框 start-->
        <bindInfo :visible="bindInfo" :Content="bindInfo.content" @del="delBook"></bindInfo>
        <!-- 删除弹框 end-->
        <!-- created by cuihd at 20180712 优化批量绑卡 添加进度条-->
        <el-dialog :title="dialogTitle" size="tiny" :visible.sync="dialogTimeout">
            <el-progress v-if="progress == '100'" :percentage="progress" status="success"></el-progress>
            <el-progress v-else :percentage="progress"></el-progress>
        </el-dialog>
    </div>
</template>

<script>
import TableLayout from 'components/TableLayout';
import { mapState, mapActions } from 'vuex';
import { mapGetters } from 'vuex';
import bindteaCard from './bindteaCard';
import batchBind from './batchTeaBind';
import batchExport from './batchTeaExport';
import bindInfo from './bindInfo';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import school from 'components/SchoolClasss/school';
import { queryTeacherCard, updateIdCard, deleteCard, batchDeleteCard, importTeacherCardProgress, importTeacherVirtualCardProgress } from 'api/cardManagement';
export default{
    name: 'teacherManage',
    components: {TableLayout, bindteaCard, batchBind, batchExport, bindInfo, province, city, region, school},
    data() {
        return {
            formInline: {// form表单数据
                fSchoolId: '',
                schoolName: '',
                fProvinceId: '',
                fAreaId: '',
                fCityId: '',
                // typeStatus: '',
                sCardNumber: '',
                userName: ''
            },
            bindInfo: {
                isShow: false,
                content: {
                    newBind: '',
                    success: ''
                }
            },
            bindCard: {
                dialogFormVisible: false
            },
            batchBind: {
                dialogFormVisible: false
            },
            batchExport: {
                dialogFormVisible: false
            },
            dialog: {
                dialogFormVisible1: false,
                dialogFormVisible2: false,
                dialogFormVisible3: false,
                dialogFormVisible4: false
            },
            statusType: [
                {
                    typeStatustId: '',
                    statusName: '全部'
                },
                {
                    typeStatustId: '1',
                    statusName: '老师'
                }
                // {
                //     typeStatustId: '2',
                //     statusName: '管理员'
                // }
            ],
            dataApply: [],
            multipleSelection: [],
            schoolNameArray: [],
            schoolloading: false,
            loading: false,
            listQuery: {// 分页
                page: 1,
                total: 0
            },
            rules: {
                fProvinceId: [{ required: true, message: '请选择省份', trigger: 'change' }],
                sCardNumber: [
                    // { pattern: /^\d{0,20}$/, message: '请输入正确的卡号', trigger: 'change' }
                ]
            },
            /**
             * created by cuihd at 20180712
             * 优化批量删除教师
             * 添加相关变量
             */
            dialogTitle: '正在批量删除学校...',
            dialogTimeout: false,
            progress: 0
        }
    },
    computed: {
        ...mapState({
            config: state => state.config.table
        }),
        ...mapGetters([
            'uid'
        ])
    },
    created() {
        console.log('11111111');
    },
    methods: {
        ...mapActions(['ChangePageSize']),
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        // 分页
        handleSizeChange(val) {
            this.ChangePageSize(val);
            this.$refs.formInline.validate((valid) => {
                if (valid) {
                    this.listQuery.page = 1;
                    this.searchFetchData();
                }
            })
        },

        handleCurrentChange(val) {
            this.loading = true;
            this.listQuery.page = val;
            this.searchFetchData();
        },

        toShowCount(item) {
            this.bindInfo.isShow = true;
            this.bindInfo.content.newBind = item.newBind;
            this.bindInfo.content.success = item.success;
        },

        delBook() {
            // 
        },

        // created by cuihd at 20180712
        // 通过此方法取得批量绑定教师卡组件的数据以进行滚动条的初始配置及进行轮询设置
        importCardState(val) {
            if (val.isTrue) {
                if (val.state == '1') {
                    this.dialogTitle = '正在批量导入教师卡...';
                    this.batchImportProgress(val);
                } else {
                    this.dialogTitle = '正在批量导入教师虚拟卡...';
                    this.batchImportVirtualProgress(val);
                }
                this.dialog.dialogFormVisible3 = false;
                // this.batchBind.dialogFormVisible = true;
                this.progress = 0;
                this.dialogTimeout = true;               
            }
        },
        // created by cuihd at 20180712
        // 轮询接口获取未导入教师卡片的数量
        batchImportProgress(obj) { // 递归轮询
            let totalNum = Number(obj.totalNum); // 强转成number类型
            importTeacherCardProgress(obj.timeStamp, obj.schoolId).then(res => {
                if (res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null) {
                    if (res.data.content != 0) {
                        this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                        setTimeout(() => {
                            this.batchImportProgress(obj);
                        }, 1000);
                    } else {
                        this.dialogTitle = '批量导入成功';
                        this.progress = 100;
                        setTimeout(() => {                       
                            this.dialogTimeout = false;
                            this.bindCardState();
                        }, 500)
                    }
                } else {
                    this.dialogTimeout = false;
                    this.$message({
                        message: '批量导入失败！',
                        type: 'error'
                    });
                }          
            }).catch(err => {
                console.log(err);
            })
        },
        // created by cuihd at 20180712
        // 轮询接口获取未导入教师卡片的数量
        batchImportVirtualProgress(obj) { // 递归轮询
            let totalNum = Number(obj.totalNum); // 强转成number类型
            importTeacherVirtualCardProgress(obj.timeStamp, obj.schoolId).then(res => {
                if (res.data.content >= 0 && res.data.content <= totalNum && res.data.content !== null) {
                    if (res.data.content != 0) {
                        this.progress = parseInt((totalNum-Number(res.data.content))/totalNum*100);
                        setTimeout(() => {
                            this.batchImportVirtualProgress(obj);
                        }, 1000);
                    } else {
                        this.dialogTitle = '批量导入成功';
                        this.progress = 100;
                        setTimeout(() => {                       
                            this.dialogTimeout = false;
                            this.toShowCount(obj);
                            this.bindCardState();
                        }, 500)
                    }
                } else {
                    this.dialogTimeout = false;
                    this.$message({
                        message: '批量导入失败！',
                        type: 'error'
                    });
                }          
            }).catch(err => {
                console.log(err);
            })
        },

        // 获取学校id
        schoolChange(val) {
            this.formInline.fSchoolId = val;
        },

        // 搜索
        searchFetchData() {
            this.loading = true;
            this.formInline.sCardNumber = this.formInline.sCardNumber.replace(/\b(0+)/gi, '');
            queryTeacherCard(this.listQuery.page, this.config.pageSize, this.formInline.fSchoolId, 
            this.formInline.fProvinceId, this.formInline.fCityId, this.formInline.fAreaId, 
            this.formInline.sCardNumber, this.formInline.userName).then((response) => {
                if (response.data.status==200) {
                    this.dataApply = response.data.content.list;
                    this.listQuery.total = response.data.content.pagination.total;
                    console.log('total', this.listQuery.total, this.dataApply);
                    this.loading = false;
                } else {
                    this.$message({
                        type: 'warning',
                        message: response.data.errorMsg
                    })
                }
            });
        },
        
        createStateFilter(query) {
            return state => {
                state.value = state.schoolName;
                return state.value.toLowerCase().includes(query.toLowerCase());
            };
        },
        // edit by cuihd at 20180712
        // 更新
        bindCardState() {
            // 从新发送请求
            if (!this.formInline.fProvinceId) {
                return;
            } else {
                this.searchFetchData();
            }           
        },

        // 单卡绑定
        goToAdd() {
            this.dialog.dialogFormVisible2 = true;
            this.bindCard.dialogFormVisible = true;
        }, 

        // 批量绑定
        goToAddRole() {
            this.dialog.dialogFormVisible3 = true;
            this.batchBind.dialogFormVisible = true;
        },

        // 批量解绑
        goToDelRole() {
            // 请选择要解绑的学生
            // this.multipleSelection
            // console.log('this.multipleSelection', this.multipleSelection);
            let roleIds = [];
            for (let i=0;i<this.multipleSelection.length;i++) {
                // roleIds.push(this.multipleSelection[i].sCardNumber); 
                roleIds.push(this.multipleSelection[i].pId); 
            }
            if (roleIds.length == 0) {
                this.$message.info('请选择要解绑的教师');
                return;
            }            
            this.$confirm('确认将选中的教师解绑?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.loading = true;
                batchDeleteCard(roleIds).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: response.data.errorMsg
                    })
                });  
            }).catch(() => {
                this.$message.info('已取消');
            });
        },

        // 批量导出
        goToExport() {
            console.log('111222');
            this.dialog.dialogFormVisible4 = true;
            this.batchExport.dialogFormVisible = true;
        },
        
        // 卡片说明
        showInstruction() {
            this.dialog.dialogFormVisible1 = true;
        },

         // 查询
        onSubmit(formInline) {// 表单查询

            this.$refs[formInline].validate((valid) => {
                if (valid) {
                    this.listQuery.page=1;
                    this.searchFetchData();
                } else {
                    return false;
                }
            });

        },

        // 设为一卡通
        toSetCard(row) {
            this.$confirm('确定将此卡设置为一卡通?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                updateIdCard(row.pId).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: '设置成功!'
                    })
                });  
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },

        // 解绑
        releaseCard(row) {
            this.$confirm('确定解除绑定?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                deleteCard(row.pId).then(response => {
                    this.searchFetchData();
                    this.$message({
                        type: 'success',
                        message: '解绑成功!'
                    })
                });  
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        }
      
    }
}
</script>
<style lang="scss" scoped>
.content {
    position: relative;
    padding: 0px;
    $bgcolor:#fff;
    .formInline {
        .formBtn{
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition{
                position: absolute;
                right:0px; 
                top: 18px;
            }
        }
    }
    .dialogTable{
        text-align: center;
        margin:0 auto;
        // margin-top: 30px;    
        th,td{
            padding: 5px 10px;
            border: solid 1px #ECECEC;
            width: 200px;
            height: 40px;
        }
        th{
            text-align: center;
            background: #f3f3f3;
        }
        tr{
            td{
                text-align: left;
                &:first-child{
                    text-align: center;
                }
            }
        }
    }
}
</style>  
